/**
 * Copyright (c) 2018 开源 All rights reserved.
 * <p>
 * https://www.sxyc.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.controller;

import io.renren.annotation.Login;
import io.renren.common.utils.Result;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.modules.yckj.common.ThreadLocalUtil;
import io.renren.modules.yckj.dto.TeamDTO;
import io.renren.modules.yckj.dto.TeamRelationDTO;
import io.renren.modules.yckj.dto.UserDTO;
import io.renren.modules.yckj.entity.TeamRelationEntity;
import io.renren.modules.yckj.enums.status.CommonStatus;
import io.renren.modules.yckj.enums.status.TeamRelationStatus;
import io.renren.modules.yckj.enums.status.TeamStatus;
import io.renren.modules.yckj.service.TeamRelationService;
import io.renren.modules.yckj.service.TeamService;
import io.renren.modules.yckj.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 测试接口
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/yckj/team")
@Tag(name = "课题组接口")
@AllArgsConstructor
public class ApiTeamController {

    private final TeamService teamService;
    private final TeamRelationService teamRelationService;
    private final UserService userService;

    @Login
    @GetMapping("search/list")
    @Operation(summary = "获取列表-搜索")
    @ApiResponse(content = @Content(mediaType = "application/json", schema = @Schema(implementation = TeamDTO.class)))
    @Parameter(name = "name", description = "名称", required = true)
    public Result<List<TeamDTO>> listOfSearch(@RequestParam("name") String name) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("userId", ThreadLocalUtil.getUserId());
        List<TeamDTO> dtoList = teamService.getSearchList(map);
        return new Result<List<TeamDTO>>().ok(dtoList);
    }

    @Login
    @GetMapping("create/list")
    @Operation(summary = "获取列表-我创建的")
    @ApiResponse(content = @Content(mediaType = "application/json", schema = @Schema(implementation = TeamDTO.class)))
    public Result<List<TeamDTO>> listOfCreate() {
        Map<String, Object> map = new HashMap<>();
        map.put("creatorId", ThreadLocalUtil.getUserId());
        List<TeamDTO> dtoList = teamService.list(map);
        return new Result<List<TeamDTO>>().ok(dtoList);
    }

    @Login
    @GetMapping("join/list")
    @Operation(summary = "获取列表-我参与的")
    @ApiResponse(content = @Content(mediaType = "application/json", schema = @Schema(implementation = TeamDTO.class)))
    public Result<List<TeamDTO>> list() {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", ThreadLocalUtil.getUserId());
        List<TeamDTO> dtoList = teamService.getTeamList(map);
        return new Result<List<TeamDTO>>().ok(dtoList);
    }


    @GetMapping("info")
    @Operation(summary = "获取信息")
    @ApiResponse(content = @Content(mediaType = "application/json",
            schema = @Schema(implementation = TeamDTO.class)))
    @Parameter(name = "id", description = "主键", required = true)
    public Result<TeamDTO> info(@RequestParam("id") Long id) {
        TeamDTO teamDTO = teamService.get(id);
        return new Result<TeamDTO>().ok(teamDTO);
    }

    @Login
    @PostMapping("save")
    @Operation(summary = "添加")
    public Result<Boolean> save(@RequestBody TeamDTO dto) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", dto.getName());
        TeamDTO teamByName = teamService.getTeamByName(map);
        if (teamByName != null) {
            return new Result<Boolean>().error("课题组名称重复，请修改。");
        }
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        dto.setCreatorId(ThreadLocalUtil.getUserId());
        dto.setCreator(ThreadLocalUtil.getUserName());
        dto.setCreateTime(new Date());
        dto.setUpdateTime(new Date());
        boolean b = teamService.save(dto);

        //把自己加入到课题组中
        TeamRelationDTO teamRelationDTO = new TeamRelationDTO();
        teamRelationDTO.setTeamId(dto.getId());
        teamRelationDTO.setTeamName(dto.getName());
        teamRelationDTO.setUserId(dto.getCreatorId());
        teamRelationDTO.setUsername(dto.getCreator());
        teamRelationDTO.setIsCreator(CommonStatus.YES.getCode());
        teamRelationDTO.setApprove(CommonStatus.YES.getCode());
        teamRelationDTO.setViewPower(CommonStatus.YES.getCode());
        teamRelationDTO.setAmountPower(CommonStatus.ALL.getCode());
        teamRelationDTO.setStatus(CommonStatus.YES.getCode());
        teamRelationDTO.setCreateTime(new Date());
        teamRelationDTO.setUpdateTime(new Date());
        b = b && teamRelationService.save(teamRelationDTO);

        return new Result<Boolean>().ok(b);
    }

    @Login
    @PostMapping("update")
    @Operation(summary = "修改")
    public Result<Boolean> update(@RequestBody TeamDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        TeamDTO dbDto = teamService.get(dto.getId());
        boolean b = false;
        if (dbDto != null && dbDto.getCreatorId().equals(ThreadLocalUtil.getUserId())) {
            dto.setUpdateTime(new Date());
            b = teamService.update(dto);
        }
        return new Result<Boolean>().ok(b);
    }

    @Login
    @GetMapping("delete")
    @Operation(summary = "删除")
    @Parameter(name = "id", description = "组id", required = true)
    public Result<Boolean> delete(@RequestParam("id") Long id) {
        TeamDTO dbDto = teamService.get(id);
        boolean b = false;
        if (dbDto != null && dbDto.getCreatorId().equals(ThreadLocalUtil.getUserId())
                && dbDto.getStatus().equals(TeamStatus.YES.getCode())) {
            if (dbDto.getDebtLimitUse().compareTo(BigDecimal.ZERO) > 0) {
                return new Result<Boolean>().error("当前组有欠款，不能解散");
            } else {
                TeamDTO update = new TeamDTO();
                update.setId(id);
                update.setStatus(TeamStatus.NO.getCode());
                b = teamService.update(update);
                return new Result<Boolean>().ok(b);
            }
        } else {
            return new Result<Boolean>().error("操作失败");
        }
    }

    @Login
    @GetMapping("apply/list")
    @Operation(summary = "获取申请列表")
    @ApiResponse(content = @Content(mediaType = "application/json", schema = @Schema(implementation = TeamDTO.class)))
    public Result<List<TeamRelationDTO>> applyList() {
        List<TeamRelationDTO> dtoList = teamRelationService.getApplyList(ThreadLocalUtil.getUserId());
        return new Result<List<TeamRelationDTO>>().ok(dtoList);
    }

    @Login
    @GetMapping("relation/list")
    @Operation(summary = "获取组员列表")
    @ApiResponse(content = @Content(mediaType = "application/json", schema = @Schema(implementation = TeamDTO.class)))
    @Parameter(name = "teamId", description = "主键", required = true)
    public Result<List<TeamRelationDTO>> relationList(@RequestParam("teamId") Long teamId) {
        Map<String, Object> map = new HashMap<>();
        map.put("teamId", teamId);
        List<TeamRelationDTO> dtoList = teamRelationService.getRelationList(map);
        return new Result<List<TeamRelationDTO>>().ok(dtoList);
    }

    @Login
    @PostMapping("relation/save")
    @Operation(summary = "组员添加")
    @Parameter(name = "teamId", description = "主键", required = true)
    @Parameter(name = "userId", description = "组员Id", required = true)
    public Result<Boolean> relationSave(@RequestParam("teamId") Long teamId, @RequestParam("userId") Long userId) {
        TeamDTO dbDto = teamService.get(teamId);
        if (dbDto != null) {
            TeamRelationEntity dbRelation = teamRelationService.getByTeamIdAndUserId(teamId, userId);
            if (dbRelation == null) {
                TeamRelationDTO dto = new TeamRelationDTO();
                dto.setTeamId(dbDto.getId());
                dto.setTeamName(dbDto.getName());
                dto.setUserId(userId);
                UserDTO userDTO = userService.get(userId);
                if (userDTO != null)
                    dto.setUsername(userDTO.getUsername());
                dto.setIsCreator(CommonStatus.NO.getCode());
                dto.setApprove(CommonStatus.NO.getCode());
                dto.setViewPower(CommonStatus.NO.getCode());
                dto.setAmountPower(CommonStatus.NO.getCode());
                dto.setStatus(CommonStatus.NO.getCode());
                dto.setCreateTime(new Date());
                dto.setUpdateTime(new Date());
                if (dbDto.getCreatorId().equals(ThreadLocalUtil.getUserId())) {
                    dto.setStatus(TeamRelationStatus.YES.getCode());
                } else {
                    dto.setStatus(TeamRelationStatus.NO.getCode());
                }
                boolean b = teamRelationService.save(dto);
                return new Result<Boolean>().ok(b);
            } else {
                return new Result<Boolean>().error("当前用户已在些课题组");
            }
        } else {
            return new Result<Boolean>().error("当前组不存在");
        }
    }

    @Login
    @PostMapping("relation/info")
    @Operation(summary = "组员信息")
    @Parameter(name = "teamId", description = "主键", required = true)
    public Result<TeamRelationEntity> relationInfo(@RequestParam("teamId") Long teamId) {
        TeamRelationEntity teamRelationEntity = teamRelationService.getByTeamIdAndUserId(teamId, ThreadLocalUtil.getUserId());
        return new Result<TeamRelationEntity>().ok(teamRelationEntity);
    }

    @Login
    @PostMapping("relation/update")
    @Operation(summary = "组员更新")
    public Result<Boolean> relationUpdate(@RequestBody TeamRelationDTO dto) {
        TeamDTO dbDto = teamService.get(dto.getTeamId());
        if (dbDto != null && dbDto.getCreatorId().equals(ThreadLocalUtil.getUserId())) {
            TeamRelationDTO teamRelationDTO = teamRelationService.get(dto.getId());
            if (teamRelationDTO != null) {
                if (teamRelationDTO.getDebtLimitUse().compareTo(BigDecimal.ZERO) > 0) {
                    return new Result<Boolean>().error("此组员有欠款，不能更新！");
                } else {
                    TeamRelationDTO dbTeamRelation = new TeamRelationDTO();
                    dbTeamRelation.setId(dto.getId());
                    dbTeamRelation.setUpdateTime(new Date());
                    dbTeamRelation.setViewPower(dto.getViewPower());
                    dbTeamRelation.setApprove(dto.getApprove());
                    dbTeamRelation.setAmountPower(dto.getAmountPower());
                    dbTeamRelation.setDebtLimit(dto.getDebtLimit());
                    boolean b = teamRelationService.update(dbTeamRelation);
                    return new Result<Boolean>().ok(b);
                }
            } else {
                return new Result<Boolean>().error("操作失败！");
            }
        } else {
            return new Result<Boolean>().error("无权限修改！");
        }
    }

    @Login
    @PostMapping("relation/pass")
    @Operation(summary = "组员申请通过")
    public Result<Boolean> relationPass(@RequestBody TeamRelationDTO dto) {
        TeamRelationDTO teamRelationDTO = teamRelationService.get(dto.getId());
        if (teamRelationDTO != null) {
            TeamRelationEntity teamRelationEntity = teamRelationService.getByTeamIdAndUserId(teamRelationDTO.getTeamId(), ThreadLocalUtil.getUserId());
            if (teamRelationEntity != null && teamRelationEntity.getApprove().equals(TeamRelationStatus.YES.getCode())) {
                TeamRelationDTO dbTeamRelation = new TeamRelationDTO();
                dbTeamRelation.setId(dto.getId());
                dbTeamRelation.setStatus(TeamRelationStatus.YES.getCode());
                boolean b = teamRelationService.update(dbTeamRelation);
                return new Result<Boolean>().ok(b);
            } else {
                return new Result<Boolean>().error("无权限操作！");
            }
        } else {
            return new Result<Boolean>().error("操作失败！");
        }
    }

    @Login
    @GetMapping("relation/delete")
    @Operation(summary = "组员删除")
    @Parameter(name = "teamId", description = "课题组Id", required = true)
    @Parameter(name = "id", description = "关系id", required = true)
    public Result<Boolean> relationDelete(@RequestParam("teamId") Long teamId, @RequestParam("id") Long id) {
        TeamDTO dbDto = teamService.get(teamId);
        boolean b = false;
        if (dbDto != null && dbDto.getCreatorId().equals(ThreadLocalUtil.getUserId())) {
            TeamRelationDTO teamRelationDTO = teamRelationService.get(id);
            if (teamRelationDTO != null) {
                if (teamRelationDTO.getDebtLimitUse().compareTo(BigDecimal.ZERO) > 0) {
                    return new Result<Boolean>().error("此组员有欠款，不能删除！");
                } else {
                    b = teamRelationService.deleteById(id);
                    return new Result<Boolean>().ok(b);
                }
            } else {
                return new Result<Boolean>().error("操作失败！");
            }
        }
        return new Result<Boolean>().ok(b);
    }
}